/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import DAO.ProductcatDAO;
import GUI.Components.IToolbarPerformEvent;
import GUI.Components.JErrorProvider;
import GUI.Components.ToolbarEvent;
import POJO.Productcat;
import POJO.Store;
import Util.DataAccessUtil;
import Util.MsgUtil;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
import org.apache.log4j.Logger;

/**
 *
 * @author Nguyễn Thi Mỷ Diện (1140214)
 */
public class FrmProductCat extends javax.swing.JInternalFrame {

    private JErrorProvider jerror;
    private Logger log = Logger.getLogger(this.getClass().getName());
    private List<Productcat> listProductCat = null;
    private final String ER_EMPTY_INPUT_PRODUCTCAT = "Bạn chưa nhập tên danh mục!";
    private final String ER_INSERT_PRODUCTCAT = "Có lỗi trong quá trình thêm!";
    private final String ER_UPDATE_PRODUCTCAT = "Có lỗi trong quá trình cập nhật!";
    private final String ER_DELETE_PRODUCTCAT = "Có lỗi trong quá trình xóa!";
    /**
     * Creates new form FrmProductCat
     */
    public FrmProductCat() {
        initComponents();
        userControlForm();
        jerror = new JErrorProvider();
        tbProductCat.setModel(new ProductCatModelTable(new ArrayList()));
        this.loadTable();
    }

    private void loadTable() {
        try {
            listProductCat = ProductcatDAO.getListProductCats(1);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex.fillInStackTrace());
            return;
        }
        getProductCatModelTable().setList(listProductCat);
    }

    private ProductCatModelTable getProductCatModelTable() {
        return (ProductCatModelTable) tbProductCat.getModel();
    }

    private void enableEditControl(boolean editing) {
        if (!editing) {
            jerror.clear();
        }
        txtProductCatName.setEnabled(editing);
        tbProductCat.setEnabled(!editing);
    }

    private void userControlForm() {
        toolbarProductCat.addEventPerformClick(new IToolbarPerformEvent() {

            @Override
            public void performEventAdd(ToolbarEvent event) {
                txtProductCatName.setText("");
                enableEditControl(true);

            }

            @Override
            public void performEventEdit(ToolbarEvent event) {
                enableEditControl(true);
            }

            @Override
            public void performEventDelete(ToolbarEvent event) {
                if(tbProductCat.getSelectedRowCount() < 1)
                    return;
               
                Productcat prodCat = 
                        getProductCatModelTable().getItem(tbProductCat.getSelectedRow());
               try {
                        DataAccessUtil.delete(prodCat);
                        MsgUtil.info("Xóa danh mục "+prodCat.getName()+" thành công!");
                        loadTable();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e.fillInStackTrace());
                        MsgUtil.error(ER_DELETE_PRODUCTCAT,e.getMessage());
                    }
            }

            @Override
            public void performEventSave(ToolbarEvent event) {
                jerror.clear();
                if (txtProductCatName.getText().isEmpty()) {
                    jerror.setError(txtProductCatName, ER_EMPTY_INPUT_PRODUCTCAT);
                    event.setIsError(true);
                    return;
                }
                Productcat prodCat = new Productcat();
                prodCat.setName(txtProductCatName.getText());
                Store store = new Store();
                store.setId(1); // tạm thời lấy store id = 1
                prodCat.setStore(store);
                if (event.isIsAdding()) {
                    try {
                        DataAccessUtil.insert(prodCat);
                        MsgUtil.info("Thêm danh mục "+prodCat.getName()+" thành công!");
                        loadTable();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e.fillInStackTrace());
                        MsgUtil.error(ER_INSERT_PRODUCTCAT,e.getMessage());
                    }
                } else if (event.isIsUpdating()) {
                    int id = (int) getProductCatModelTable()
                                .getValueAt(tbProductCat.getSelectedRow(), 0);
                    prodCat.setId(id); 
                    try {
                        DataAccessUtil.update(prodCat);
                        MsgUtil.info("Cập nhật danh mục thành công!");
                        loadTable();
                    } catch (Exception e) {
                        log.error(e.getMessage(), e.fillInStackTrace());
                         MsgUtil.error(ER_UPDATE_PRODUCTCAT,e.getMessage());
                    }
                }
                enableEditControl(false);
            }

            @Override
            public void performEventCancel(ToolbarEvent event) {
                enableEditControl(false);
            }

            @Override
            public void performEventRefresh(ToolbarEvent event) {
            }

            @Override
            public void performEventClose(ToolbarEvent event) {
                dispose();
            }
        });
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbProductCat = new javax.swing.JTable();
        toolbarProductCat = new GUI.Components.Toolbar();
        jPanel2 = new javax.swing.JPanel();
        txtProductCatName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setTitle("Danh mục sản phẩm");

        tbProductCat.setAutoCreateRowSorter(true);
        tbProductCat.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Mã danh mục", "Tên danh mục"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tbProductCat.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbProductCatMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tbProductCat);
        tbProductCat.getColumnModel().getColumn(0).setResizable(false);
        tbProductCat.getColumnModel().getColumn(0).setPreferredWidth(120);
        tbProductCat.getColumnModel().getColumn(1).setResizable(false);
        tbProductCat.getColumnModel().getColumn(1).setPreferredWidth(400);

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Thông tin danh mục", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N

        txtProductCatName.setEnabled(false);
        txtProductCatName.setName("jTextField_TenCuaHang");
        txtProductCatName.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtProductCatNameActionPerformed(evt);
            }
        });

        jLabel1.setText("Tên danh mục:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(txtProductCatName, javax.swing.GroupLayout.PREFERRED_SIZE, 180, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtProductCatName)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolbarProductCat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 66, Short.MAX_VALUE))
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(toolbarProductCat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 62, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void txtProductCatNameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtProductCatNameActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtProductCatNameActionPerformed

    private void tbProductCatMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbProductCatMouseClicked

        txtProductCatName.setText(
                (String) getProductCatModelTable()
                        .getValueAt(tbProductCat.getSelectedRow(), 1));
    }//GEN-LAST:event_tbProductCatMouseClicked
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tbProductCat;
    private GUI.Components.Toolbar toolbarProductCat;
    private javax.swing.JTextField txtProductCatName;
    // End of variables declaration//GEN-END:variables
}

//<editor-fold defaultstate="collapsed" desc="Productcat model table">
class ProductCatModelTable extends AbstractTableModel {

    private static final String[] columnNames = {"Mã danh mục", "Tên danh mục"};
    private List<Productcat> list;

    public ProductCatModelTable(List<Productcat> list) {
        this.list = list;
    }

    public List<Productcat> getList() {
        return this.list;
    }
    public Productcat getItem(int rowIndex){
        return this.list.get(rowIndex);
    }
    public void setList(List<Productcat> list) {
        this.list = list;
        fireTableDataChanged();
    }

    public void removeAllElement() {
        this.list.clear();
        fireTableDataChanged();
    }

    public void addElement(Productcat e) {
        // Adds the element in the last position in the list
        list.add(e);
        fireTableRowsInserted(list.size() - 1, list.size() - 1);
    }

    public void removeElement(int rowIndex) {
        list.remove(rowIndex);
        fireTableRowsDeleted(rowIndex, rowIndex);
    }

    @Override
    public int getRowCount() {
        return list.size();
    }

    @Override
    public int getColumnCount() {
        return columnNames.length;
    }

    @Override
    public String getColumnName(int index) {
        return columnNames[index];
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        switch (columnIndex) {
            case 0:
                return list.get(rowIndex).getId();
            case 1:
                return list.get(rowIndex).getName();
        }
        return null;
    }
}
//</editor-fold>
